#include <minix/drivers.h>
#include <minix/vtreefs.h>
#include <sys/stat.h>
#include "bencode.h"
#include "modify_structs.h"

#ifndef OK
#define OK 0
#endif

entry_ptr root;

void rss_init_hook() {
	/*
	 * Prepareer het bestandssysteem door alle top-level key-valueparen
	 * te doorlopen en om te zetten in naam-inhoud van bestanden.
	 */
	dict_entry_ptr it;
	for (it = root->data.dictionary->first; it != NULL; it = it->next) {
		char *data = to_string(it->value);
		char *name = (char*)(it->name);

		/* zoek naar een guid in dit element om een mooie naam te vinden */
		if (it->value->type == TYPE_DICTIONARY) {
			entry_ptr entry = dictionary_find(it->value, "guid");

			if (entry != NULL && entry->type == TYPE_STRING) {
				/* guid gevonden, nu het deel na de laatste / als naam nemen als het een URI betreft */
				char *ptr = strrchr((char*)*(entry->data.string), '/');

				name = (ptr == NULL) ? (char*)*(entry->data.string) : ptr+1;
			}

			entry = dictionary_find(it->value, "pubDate");
			if (entry != NULL && entry->type == TYPE_STRING) {
				char *ptr = strchr((char*)*(entry->data.string), ',');

			}
		}

		struct inode_stat *stat_ptr = (struct inode_stat*)malloc(sizeof(struct inode_stat));
		stat_ptr->mode = S_IFREG | 0444;
		stat_ptr->uid = 0;
		stat_ptr->gid = 0;
		stat_ptr->size = strlen(data);
		stat_ptr->dev = NO_DEV;

		add_inode(get_root_inode(), name, NO_INDEX, stat_ptr, 0, (cbdata_t)data);
	}
}

int rss_read_hook(struct inode *inode, off_t offset, char **ptr, size_t *len, cbdata_t cbdata) {
	char *data = (char*) cbdata;
	struct inode_stat *stat_ptr;
	*ptr = data + offset;
	get_inode_stat(inode, stat_ptr);

	if(*len > stat_ptr->size-offset) {
		*len = stat_ptr->size-offset;
	}
	return OK;
}

int main(int argc, char **argv) {
	char *fname = (argc > 1) ? argv[1] : "file.ben";

	FILE *file = fopen(fname, "r");
		root = parse_bencode_file(file);
	fclose(file);
	
	if (root != NULL) {
		struct inode_stat root_stat = {
			S_IFDIR | 0555,
			0,
			0,
			0,
			NO_DEV
		};

		struct fs_hooks my_hooks = {
			rss_init_hook,
			NULL,
			NULL,
			NULL,
			rss_read_hook,
			NULL,
			NULL
		};
		start_vtreefs(&my_hooks, 10, &root_stat, 0);

		return 0;
	}
	else {
		return -1;
	}
}
